﻿using System.Text;

namespace RemoteSensingImageDirectServer.Register.Http
{
    public class CorsMiddleware
    {
        private readonly RequestDelegate _next;

        private readonly string _origin = "*";

        private readonly string _method = "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS";

        private readonly string _accept = "text/html,application/xhtml+xml,application/xml;"
            + "q=0.9,image/avif,image/webp,image/apng,*/*;"
            + "q=0.8,application/signed-exchange;"
            + "v=b3;q=0.7";

        public CorsMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        ~CorsMiddleware()
        {
        }

        public async Task Invoke(HttpContext context)
        {
            if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", _origin);
            }

            if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Methods"))
            {
                context.Response.Headers.Add("Access-Control-Allow-Methods", _method);
            }

            context.Request.Headers["Accept"] = _accept;


            var Request_URL = new StringBuilder()
                .Append(context.Request.Scheme)
                .Append("://")
                .Append(context.Request.Host)
                .Append(context.Request.PathBase)
                .Append(context.Request.Path)
                .Append(context.Request.QueryString)
                .ToString();

            Console.WriteLine(Request_URL);
            Request_URL = null;

            await _next(context);

        }
    }
}
